<?php

namespace Sharks\Core\Http;

use Sharks\Core\AppContext;

/**
 * Flash数据。使用Session跨Route传递数据
 *
 * 使用 Flash::class 作为Session前辍。即为: '\Sharks\Core\Http\Flash'
 */
class Flash {

    private $app;

    public function __construct(AppContext $app) {
        $this->app = $app;
    }

    /**
     * 提取数据, 提取后自动遗忘;如数据项不存在,则返回默认值
     * @param $name
     * @param $default
     * @return mixed|null
     */
    public function get($name, $default = null) {
        if ($this->app->session()->has("__FLASH__" . $name)) {
            return unserialize($this->app->session()->forget("__FLASH__" . $name));
        }
        return $default;
    }

    public function put($name, $value) {
        $this->app->session()->put("__FLASH__" . $name, serialize($value));
    }

    public function has($name) {
        return $this->app->session()->has("__FLASH__" . $name);
    }
}